package cn.zimo.cityinhand;

import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;

import java.util.ArrayList;
import java.util.List;

import cn.zimo.cityinhand.activity.LoginActivity;
import cn.zimo.cityinhand.activity.permission.HiPermission;
import cn.zimo.cityinhand.config.HttpConfig;
import cn.zimo.cityinhand.fragment.IndexFragment;
import cn.zimo.cityinhand.fragment.MessageFragment;
import cn.zimo.cityinhand.fragment.MyFragment;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

/**
 * @author 子墨
 * @datetime 2018/9/22 9:52
 * @description 底部导航
 */
public class BottomNavigationActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {


    // 试试ssh
    private FrameLayout content;

    private Fragment mIndexFragment;
    private Fragment mMessageFragment;
    private Fragment mMyFragment;
    private Fragment currentFragment;

    private Activity context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_navigation);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        context = this;

        SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
        if (sharedPreferences != null){
            HttpConfig.Sign = sharedPreferences.getString("sign",null);
            HttpConfig.SessionId = sharedPreferences.getString("sessionid",null);
            Long loginTime = sharedPreferences.getLong("loginTime",0);
            // 判断是否七天过后
            Long now = System.currentTimeMillis();
            if (now - loginTime > 24*60*60*1000){
                // 过时了
                HttpConfig.Sign = null;
                HttpConfig.SessionId = null;
            }
        }

        /**
         * Android6.0+，检查动态权限
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

            checkPermissions();

        }

        content = findViewById(R.id.content);
        // 设置底部导航栏
        BottomNavigationBar navigation = findViewById(R.id.navigation);
        navigation
                .setTabSelectedListener(this)// 点击事件监听
                .setMode(BottomNavigationBar.MODE_DEFAULT)// 切换模式：未选中的Item不显示文字，选中的显示文字，有切换动画效果。
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE)// 波纹样式 点击有波纹效果
                .setActiveColor(R.color.navigation_background) // 背景颜色
                .setBarBackgroundColor(R.color.navigation_selected);// 选中颜色

        /*
        * @author 方少
        * @describe 消息气泡
        * */
        //气泡
        TextBadgeItem mBadgeItem = new TextBadgeItem()
                .setAnimationDuration(200)
                .setBackgroundColor(Color.RED)
                .setHideOnSelect(false)
                .setText("10");
        // 添加导航按钮
        navigation
                .addItem(new BottomNavigationItem(R.drawable.icon_index,"主页"))
                .addItem(new BottomNavigationItem(R.drawable.icon_message,"消息").setBadgeItem(mBadgeItem))
                .addItem(new BottomNavigationItem(R.drawable.icon_my,"个人"))
                .setFirstSelectedPosition(0)
                .initialise();

        mIndexFragment = new IndexFragment();
        mMessageFragment = new MessageFragment();
        mMyFragment = new MyFragment();

        setDefaultFragment();
    }

    private void checkPermissions() {

        // 要申请的动态权限集合
        List<PermissionItem> permissionItems = new ArrayList<PermissionItem>();
        permissionItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "存储", R.drawable.permission_ic_storage));
        permissionItems.add(new PermissionItem(Manifest.permission.CAMERA, "照相机", R.drawable.permission_ic_camera));
        permissionItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, "定位", R.drawable.permission_ic_location));
        // 申请动态权限，实现回调接口
        HiPermission
                .create(this)
                .permissions(permissionItems)
                .title("你好")
                .msg("为了保证正常使用本应用，请允许所有相关权限")
                .animStyle(R.style.PermissionAnimScale)
                .style(R.style.PermissionDefaultNormalStyle)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {
                        Toast.makeText(getApplicationContext(),"没有权限本应用无法正常启动，请重启本应用授权或者到设置中手动开启",Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFinish() {
                    }

                    @Override
                    public void onDeny(String permission, int position) {
                        Toast.makeText(getApplicationContext(),"没有权限本应用无法正常启动，请重启本应用授权或者到设置中手动开启",Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onGuarantee(String permission, int position) {

                    }
                });
    }

    private void setDefaultFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.content,mIndexFragment);
        transaction.commit();
        // 当前是indexfragment
        currentFragment = mIndexFragment;
    }

    @Override
    public void onTabSelected(int position) {
        if (HttpConfig.Sign == null || HttpConfig.SessionId == null){
            Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
            return;
        }
        switch (position) {
            case 0:
                if (mIndexFragment == null) {
                    mIndexFragment = new IndexFragment();
                }
                switchFragment(currentFragment,mIndexFragment);
                break;

            case 1:
                if (mMessageFragment == null) {
                    mMessageFragment = new MessageFragment();
                }
                switchFragment(currentFragment,mMessageFragment);
                break;
            case 2:
                if (mMyFragment == null) {
                    mMyFragment = new MyFragment();
                }
                switchFragment(currentFragment,mMyFragment);
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    public void switchFragment(Fragment from, Fragment to) {
        if (currentFragment != to) {
            currentFragment = to;
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            if (!to.isAdded()) {
                transaction
                        .hide(from)
                        .add(R.id.content, to)
                        .commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction
                        .hide(from)
                        .show(to)
                        .commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }
}
